//
//  UIColorLmyExtension.swift
//  limuyun
//
//  Created by limuyun on 2016/12/20.
//  Copyright © 2016年 biiway. All rights reserved.
//

import UIKit

public extension UIColor {
    
    /// RGB颜色
    ///
    /// - Parameters:
    ///   - r: red  0-255
    ///   - g: green 0-255
    ///   - b: blue 0-255
    /// - Returns: UIColor
    class func RGB (_ r:CGFloat,_ g:CGFloat,_ b:CGFloat) -> UIColor {
        return self.RGBA(r, g, b, 1)
    }
    
    class func RGBA (_ r:CGFloat,_ g:CGFloat,_ b:CGFloat,_ a:CGFloat) -> UIColor{
        return UIColor(red: r/255.0, green: g/255.0, blue: b/255.0, alpha: a)
    }
    
    /// 16进制颜色字符串转换成RGB颜色
    ///
    /// - Parameter colorStr: String? ,16进制颜色值:(例"9B30FF" 或 "#9B30FF")
    /// - Returns: UIColor
    class func color_fromHexColorString(_ colorStr:String?) -> UIColor {
        return self.color_fromHexColorString(colorStr, alpha: 1)
    }
    class func color_fromHexColorString(_ colorStr:String?, alpha: CGFloat) -> UIColor {
        
         if let color_str = colorStr {
                if color_str.isEmpty {
                       return UIColor.clear
                   }
                   
                   var cString = color_str.trimmingCharacters(in: NSCharacterSet.whitespacesAndNewlines)
                   
                   if cString.count == 0 {
                       return UIColor.clear
                   }
                   
                   if cString.hasPrefix("#") {
                       cString.remove(at: cString.startIndex)
                   }
                   
                   if cString.count < 6 && cString.count != 6 {
                       
                       return UIColor.clear
                   }
                   
                   let value = "0x\(cString)"
                   
                   let scanner = Scanner(string:value)
                   
                   var hexValue : UInt64 = 0
                   //查找16进制是否存在
                   if scanner.scanHexInt64(&hexValue) {
                       print(hexValue)
                       let redValue = CGFloat((hexValue & 0xFF0000) >> 16)/255.0
                         let greenValue = CGFloat((hexValue & 0xFF00) >> 8)/255.0
                         let blueValue = CGFloat(hexValue & 0xFF)/255.0
                         return UIColor(red: redValue, green: greenValue, blue: blueValue, alpha: alpha)
                   }else {
                       return UIColor.clear
                   }
               }
               return UIColor.black
           }
    
    
}
